<template>
  <div 
    ref="editableDiv"
    class="editable-div"
    contenteditable="true"
    @input="handleInput"
    @blur="handleBlur"
    @focus="handleFocus"
  ></div>
</template>

<script>
export default {
  name: 'EditableDiv',
  props: {
    value: {
      type: String,
      default: ''
    }
  },
  data() {
    return {
      rawContent: this.value,
      isEditing: false // 标记是否正在编辑
    }
  },
  methods: {
    handleInput() {
      // 获取原始文本内容
      this.rawContent = this.$refs.editableDiv.textContent;
      this.$emit('input', this.rawContent);
    },
    handleFocus() {
      // 进入编辑状态，取消格式化显示原始文本
      this.isEditing = true;
      // 从父组件获取最新值并显示原始文本
      this.rawContent = this.value;
      this.$refs.editableDiv.textContent = this.rawContent;
      this.setCursorToEnd();
    },
    handleBlur() {
      // 退出编辑状态，应用格式化
      this.isEditing = false;
      this.$emit('blur', this.rawContent);
      this.updateFormattedContent();
    },
    updateFormattedContent() {
      if (this.isEditing) return; // 编辑中不更新格式
      
      const regex = /\[DESC.*?\]/g;
      
      if (regex.test(this.rawContent)) {
        const formatted = this.rawContent.replace(regex, (match) => {
          return `<span class="blue-text">${match}</span>`;
        });
        this.$refs.editableDiv.innerHTML = formatted;
      } else {
        this.$refs.editableDiv.textContent = this.rawContent;
      }
    },
    setCursorToEnd() {
      // 仅在有内容时设置光标位置
      if (this.$refs.editableDiv.childNodes.length > 0) {
        const range = document.createRange();
        const selection = window.getSelection();
        range.setStartAfter(this.$refs.editableDiv.lastChild);
        range.collapse(true);
        selection.removeAllRanges();
        selection.addRange(range);
      }
    }
  },
  mounted() {
    // 组件初始化时执行一次格式化
    this.rawContent = this.value;
    this.updateFormattedContent();
  }
}
</script>

<style scoped>
.editable-div {
  min-height: 60px;
  padding: 8px 12px;
  border: 1px solid #ddd;
  border-radius: 4px;
  outline: none;
  transition: border-color 0.2s;
}

.editable-div:focus {
  border-color: #42b983;
  box-shadow: 0 0 0 2px rgba(66, 185, 131, 0.2);
}

/* 穿透scoped限制 */
::v-deep .blue-text {
  color: #2196F3;
  font-weight: 500;
}
</style>
